import React, { PropTypes } from 'react'
import _ from 'lodash'

class FileInput extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      files:[]
    }
    this.onUploadHandle = this.onUpload.bind(this)
    this.onChangeHandle = this.onChange.bind(this)
  }

  onChange(e) {
    e.preventDefault()

    let fs = e.target.files||[]
    let fsLen = fs.length
    for (let i = 0; i < fsLen; i++) {
      fs[i].thumb = window.URL.createObjectURL(fs[i])
    }

    this.setState({ files:fs })
  }

  onUpload(e) {
    e.preventDefault()
    this.props.onUpload(this.state.files)
  }

  render() {
    return (
      <div>
        <input type='file' multiple={true} accept='image/jpeg' onChange={this.onChangeHandle} />
        <div onClick={this.onUploadHandle}>上传</div>
        {
          _.map(this.state.files, (v,k) => {
            return (
              <div key={k}>
                <img src={v.thumb} />
              </div>
            )
          })
        }
      </div>
    )
  }
}

FileInput.propTypes = {
  onUpload: PropTypes.func.isRequired,
}

/*
 https://github.com/rockuw/oss-in-browser/blob/master/app.js
* */

export default FileInput
